// 考试页面JavaScript

// 全局变量
let quizData = [];
let currentQuestionIndex = 0;
let score = 0;
let timeLeft = 0;
let totalTime = 0;
let timerInterval = null;
let userAnswers = [];

document.addEventListener('DOMContentLoaded', function() {
    // 从本地存储获取考试参数
    const quizParams = JSON.parse(localStorage.getItem('quizParams'));
    if (!quizParams) {
        alert('请先设置考试参数！');
        window.location.href = '/';
        return;
    }
    
    // 绑定事件
    document.getElementById('submit-btn').addEventListener('click', submitAnswer);
    document.getElementById('next-btn').addEventListener('click', nextQuestion);
    
    // 初始化考试
    initializeQuiz(quizParams);
});

// 初始化考试
function initializeQuiz(params) {
    // 设置题目总数
    document.getElementById('total-questions').textContent = params.count === 'all' ? '全部' : params.count;
    
    // 生成考试数据
    generateQuizData(params);
}

// 生成考试数据
function generateQuizData(params) {
    // 从后端获取单词数据
    fetch('/api/words?' + new URLSearchParams({
        levels: params.levels,
        units: params.units
    }))
    .then(response => response.json())
    .then(words => {
        // 根据题目数量筛选单词
        let selectedWords = words;
        if (params.count !== 'all') {
            const count = parseInt(params.count);
            // 如果请求数量小于单词总数，随机选择
            if (count < words.length) {
                selectedWords = [];
                const shuffled = [...words].sort(() => 0.5 - Math.random());
                selectedWords = shuffled.slice(0, count);
            }
        }
        
        // 为每个单词生成题目
        selectedWords.forEach((word, index) => {
            // 随机选择题型，排除无意义的题型（如看图选图）
            let availableTypes = params.types.filter(type => type !== 'image-image' && type !== 'audio-audio');
            // 确保至少有一个有效题型
            if (availableTypes.length === 0) {
                availableTypes = ['word-image', 'image-word'];
            }
            const randomType = availableTypes[Math.floor(Math.random() * availableTypes.length)];
            
            // 创建题目数据
            const question = {
                id: word.id,
                type: randomType,
                word: word.word,
                level: word.level,
                unit: word.unit,
                options: generateOptions(randomType, word.word, words)
            };
            
            quizData.push(question);
        });
        
        // 设置题目总数
        document.getElementById('total-questions').textContent = quizData.length;
        
        // 设置倒计时（每题30秒）
        totalTime = quizData.length * 30;
        timeLeft = totalTime;
        updateTimerDisplay();
        
        // 启动计时器
        startTimer();
        
        // 显示第一题
        showQuestion(0);
    })
    .catch(error => {
        console.error('获取单词数据失败:', error);
        alert('获取单词数据失败，请重试！');
        // 如果获取数据失败，使用模拟数据
        useMockData(params);
    });
}

// 获取随机单词
function getRandomWord() {
    const words = ['alligator', 'ant', 'apple', 'ax', 'banana', 'bear', 'bed', 'bird', 'car', 'cat'];
    return words[Math.floor(Math.random() * words.length)];
}

// 使用模拟数据
function useMockData(params) {
    // 生成模拟数据
    const mockWords = [
        {id: 1, level: 1, unit: 1, word: 'apple'},
        {id: 2, level: 1, unit: 1, word: 'banana'},
        {id: 3, level: 1, unit: 2, word: 'cat'},
        {id: 4, level: 1, unit: 2, word: 'dog'},
        {id: 5, level: 2, unit: 1, word: 'elephant'},
        {id: 6, level: 2, unit: 1, word: 'fish'}
    ];
    
    // 根据参数筛选数据
    let filteredWords = mockWords;
    if (params.levels && params.levels.length > 0) {
        filteredWords = filteredWords.filter(w => params.levels.includes(w.level));
    }
    if (params.units && params.units.length > 0) {
        filteredWords = filteredWords.filter(w => params.units.includes(w.unit));
    }
    
    // 根据题目数量筛选单词
    let selectedWords = filteredWords;
    if (params.count !== 'all') {
        const count = parseInt(params.count);
        // 如果请求数量小于单词总数，随机选择
        if (count < filteredWords.length) {
            selectedWords = [];
            const shuffled = [...filteredWords].sort(() => 0.5 - Math.random());
            selectedWords = shuffled.slice(0, count);
        }
    }
    
    // 为每个单词生成题目
    selectedWords.forEach((word, index) => {
        // 随机选择题型，排除无意义的题型（如看图选图）
        let availableTypes = params.types.filter(type => type !== 'image-image' && type !== 'audio-audio');
        // 确保至少有一个有效题型
        if (availableTypes.length === 0) {
            availableTypes = ['word-image', 'image-word'];
        }
        const randomType = availableTypes[Math.floor(Math.random() * availableTypes.length)];
        
        // 创建题目数据
        const question = {
            id: word.id,
            type: randomType,
            word: word.word,
            level: word.level,
            unit: word.unit,
            options: generateOptions(randomType, word.word, mockWords)
        };
        
        quizData.push(question);
    });
    
    // 设置题目总数
    document.getElementById('total-questions').textContent = quizData.length;
    
    // 设置倒计时（每题30秒）
    totalTime = quizData.length * 30;
    timeLeft = totalTime;
    updateTimerDisplay();
    
    // 启动计时器
    startTimer();
    
    // 显示第一题
    showQuestion(0);
}

// 生成选项
function generateOptions(type, correctWord, allWords) {
    const options = [];
    
    // 添加正确答案
    options.push({
        text: correctWord,
        isCorrect: true
    });
    
    // 添加3个错误答案
    const wrongWords = allWords.filter(word => word.word !== correctWord);
    const shuffledWrongWords = shuffleArray(wrongWords);
    
    for (let i = 0; i < Math.min(3, shuffledWrongWords.length); i++) {
        options.push({
            text: shuffledWrongWords[i].word,
            isCorrect: false
        });
    }
    
    // 如果选项不足4个，添加随机单词
    while (options.length < 4) {
        const randomWords = ['alligator', 'ant', 'apple', 'ax', 'banana', 'bear', 'bed', 'bird', 'car', 'cat'];
        const randomWord = randomWords[Math.floor(Math.random() * randomWords.length)];
        if (!options.find(opt => opt.text === randomWord)) {
            options.push({
                text: randomWord,
                isCorrect: false
            });
        }
    }
    
    // 打乱选项顺序
    return shuffleArray(options);
}

// 打乱数组
function shuffleArray(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
}

// 显示题目
function showQuestion(index) {
    const question = quizData[index];
    if (!question) return;
    
    currentQuestionIndex = index;
    
    // 更新进度
    document.getElementById('current-question').textContent = index + 1;
    
    // 更新题目提示
    const promptElement = document.getElementById('question-prompt');
    switch (question.type) {
        case 'word-image':
            promptElement.textContent = '请选择与单词对应的图片';
            break;
        case 'image-word':
            promptElement.textContent = '请选择图片对应的单词';
            break;
        case 'word-audio':
            promptElement.textContent = '请选择与单词对应的音频';
            break;
        case 'audio-word':
            promptElement.textContent = '请选择音频对应的单词';
            break;
        case 'image-audio':
            promptElement.textContent = '请选择与图片对应的音频';
            break;
        case 'audio-image':
            promptElement.textContent = '请选择与音频对应的图片';
            break;
        default:
            promptElement.textContent = '请选择正确答案';
    }
    
    // 更新媒体内容
    const mediaElement = document.getElementById('question-media');
    mediaElement.innerHTML = '';
    
    // 对于需要显示单词的题型，添加单词显示
    if (question.type === 'word-image' || question.type === 'word-audio') {
        const wordElement = document.createElement('div');
        wordElement.className = 'question-word';
        wordElement.textContent = question.word;
        mediaElement.appendChild(wordElement);
    }
    
    // 根据题型显示不同内容
    switch (question.type) {
        case 'word-image':
        case 'image-word':
        case 'image-audio':
            // 显示图片
            const img = document.createElement('img');
            img.src = `/static/images/${question.word}.jpg`;
            img.alt = question.word;
            img.className = 'question-image';
            mediaElement.appendChild(img);
            break;
        case 'word-audio':
        case 'audio-word':
        case 'audio-image':
            // 显示音频播放器
            const audioContainer = document.createElement('div');
            audioContainer.className = 'audio-player';
            audioContainer.innerHTML = `
                <button onclick="playAudio('${question.word}', 1)">播放音频</button>
                <button onclick="playAudio('${question.word}', 0.5)" class="speed-control">慢速播放</button>
                <audio id="audio-${question.word}" src="/static/audio/${question.word}.mp3"></audio>
            `;
            mediaElement.appendChild(audioContainer);
            break;
    }
    
    // 生成选项
    const optionsContainer = document.getElementById('options-container');
    optionsContainer.innerHTML = '';
    
    question.options.forEach((option, i) => {
        const optionElement = document.createElement('div');
        optionElement.className = 'option';
        optionElement.dataset.index = i;
        
        // 根据题型显示不同内容
        switch (question.type) {
            case 'word-image':
            case 'audio-image':
                // 显示图片选项
                optionElement.innerHTML = `
                    <img src="/static/images/${option.text}.jpg" alt="${option.text}" class="option-image">
                `;
                break;
            case 'image-word':
            case 'audio-word':
            case 'word-audio':
            case 'image-audio':
                // 显示文字选项
                optionElement.innerHTML = `
                    <div>${option.text}</div>
                `;
                break;
        }
        
        optionElement.addEventListener('click', function() {
            // 清除之前的选择
            document.querySelectorAll('.option').forEach(opt => {
                opt.classList.remove('selected');
            });
            
            // 标记当前选择
            this.classList.add('selected');
        });
        
        optionsContainer.appendChild(optionElement);
    });
    
    // 重置按钮状态
    document.getElementById('submit-btn').style.display = 'inline-block';
    document.getElementById('next-btn').style.display = 'none';
}

// 播放音频
function playAudio(word, speed = 1) {
    const audio = document.getElementById(`audio-${word}`);
    if (audio) {
        audio.playbackRate = speed;
        audio.play();
        
        // 更新按钮状态
        const normalButton = document.querySelector(`#question-media button:not(.speed-control)`);
        const speedButton = document.querySelector(`#question-media .speed-control`);
        
        if (speedButton) {
            if (speed === 0.5) {
                speedButton.classList.add('active');
            } else {
                speedButton.classList.remove('active');
            }
        }
    }
}

// 提交答案
function submitAnswer() {
    const selectedOption = document.querySelector('.option.selected');
    if (!selectedOption) {
        alert('请先选择一个答案！');
        return;
    }
    
    const question = quizData[currentQuestionIndex];
    const selectedIndex = parseInt(selectedOption.dataset.index);
    const isCorrect = question.options[selectedIndex].isCorrect;
    
    // 记录答案
    userAnswers[currentQuestionIndex] = {
        questionId: question.id,
        selectedOption: selectedIndex,
        isCorrect: isCorrect
    };
    
    // 更新得分
    if (isCorrect) {
        score++;
        document.getElementById('score').textContent = score;
    }
    
    // 显示正确答案
    showCorrectAnswer(selectedIndex, question);
    
    // 如果答对且不是最后一题，自动进入下一题
    if (isCorrect && currentQuestionIndex < quizData.length - 1) {
        // 延迟1秒后自动进入下一题
        setTimeout(() => {
            nextQuestion();
        }, 1000);
    } else {
        // 切换按钮
        document.getElementById('submit-btn').style.display = 'none';
        document.getElementById('next-btn').style.display = 'inline-block';
    }
}

// 显示正确答案
function showCorrectAnswer(selectedIndex, question) {
    // 高亮正确答案
    const options = document.querySelectorAll('.option');
    const correctIndex = question.options.findIndex(opt => opt.isCorrect);
    
    if (correctIndex !== -1) {
        options[correctIndex].style.backgroundColor = '#2ecc71';
        options[correctIndex].style.color = 'white';
    }
    
    // 如果选择错误，高亮错误选项
    if (selectedIndex !== correctIndex) {
        options[selectedIndex].style.backgroundColor = '#e74c3c';
        options[selectedIndex].style.color = 'white';
    }
}

// 下一题
function nextQuestion() {
    if (currentQuestionIndex < quizData.length - 1) {
        showQuestion(currentQuestionIndex + 1);
    } else {
        // 考试结束
        finishQuiz();
    }
}

// 启动计时器
function startTimer() {
    timerInterval = setInterval(() => {
        timeLeft--;
        updateTimerDisplay();
        
        if (timeLeft <= 0) {
            clearInterval(timerInterval);
            finishQuiz();
        }
    }, 1000);
}

// 更新计时器显示
function updateTimerDisplay() {
    const minutes = Math.floor(timeLeft / 60);
    const seconds = timeLeft % 60;
    document.getElementById('time-left').textContent = 
        `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}

// 结束考试
function finishQuiz() {
    clearInterval(timerInterval);
    
    // 保存考试结果到本地存储
    const results = {
        score: score,
        total: quizData.length,
        timeTaken: totalTime - timeLeft,
        answers: userAnswers
    };
    
    localStorage.setItem('quizResults', JSON.stringify(results));
    
    // 跳转到结果页面
    window.location.href = '/results';
}